import plugin from '../../../lib/plugins/plugin.js'
import _ from "lodash"
import puppeteer from 'puppeteer'
import { createRequire } from 'module'
import setting from '../model/setting.js'

const require = createRequire(import.meta.url)

export class webPreview extends plugin {
    constructor() {
        super({
            name: '[碎月]截图预览网页内容',
            dsc: '群里发送网页地址，截图预览网页内容',
            event: 'message',
            priority: 1006,
            rule: [
                {
                    reg: '^(?:(http|https):\/\/)?((?:[\\w-]+\\.)+[a-z0-9]+)((?:\/[^\/?#]*)+)?(\\?[^#]+)?(#.+)?$',
                    fnc: 'webPreview'
                },
                {
                    reg: '^#?百度(.*)$',
                    fnc: 'baiduWeb'
                },
            ]
        })
    }
    get appconfig() { return setting.getConfig("config") }

    getPuppeteerOptions() {
        return {
            headless: true,
            args: [
                '--disable-gpu',
                '--disable-dev-shm-usage',
                '--disable-setuid-sandbox',
                '--no-first-run',
                '--no-sandbox',
                '--no-zygote',
                '--single-process',
                '--incognito'
            ]
        }
    }
    async webPreview() {
        // await this.e.reply(`[碎月]开始截图网页，这可能需要一些时间，请稍等...`, true)
        const browser = await puppeteer.launch(this.getPuppeteerOptions())
        const page = await browser.newPage()
        await page.goto(this.e.msg)
        await page.setViewport({
            width: this.appconfig['width'],
            height: this.appconfig['height']
        })
        await this.reply(segment.image(await page.screenshot({
            fullPage: true
        })))
        await browser.close()
        return true
    }
    async baiduWeb() {
        // await this.e.reply(`[碎月]开始搜索并截图百度网页，请稍等...`, true);
        try {
            const browser = await puppeteer.launch(this.getPuppeteerOptions());
            const page = await browser.newPage();

            let webkeywd = this.e.msg.replace(/#|百度/gm, '');
            webkeywd = webkeywd.replace(/，| |,/g, ",");
            let wdKey = webkeywd.split(",");
            wdKey = _.compact(wdKey);

            let searchKey = wdKey[0];
            let keyWd = wdKey[1];

            let weburl = `https://www.baidu.com/s?wd=${searchKey ? searchKey : webkeywd}`;

            await page.goto(weburl);
            await page.setViewport({
                width: this.appconfig['width'],
                height: this.appconfig['height']
            })
            if (keyWd != '列表') {
                try {
                    await page.waitForSelector('.result a');
                    let link = await page.evaluate(async keyWd => {
                        let links = [...document.querySelectorAll('.result a')].filter(item => {
                            return item.innerText && item.innerText.includes(keyWd)
                        });
                        return links.length > 0 ? links[0].toString() : null;
                    }, keyWd);

                    if (link) {
                        link = link.toString();
                    } else {
                        link = weburl;
                    }
                    console.log(link);

                    await page.goto(link);
                } catch (error) {
                    console.error(error);
                }
            }
            await this.e.reply(segment.image(await page.screenshot({ fullPage: true })))

            await browser.close();
        } catch (error) {
            // await this.e.reply(`[碎月]百度截图的网页访问失败或不是一个可访问的网站`)
            logger.error('[碎月]截图发生了错误:', error)
        }
    }
}